import 'whatwg-fetch'
import { ElMessage } from 'element-plus'
import { useCommonStore } from '@/store/common'

const commonStore = useCommonStore()

export const request = (url = '', option: RequestInit = {}, needLoading = true) => {
  needLoading && commonStore.incrementRequestTimes()

  return new Promise((resolve: (obj: ObjectType) => void) => {
    const controller = new AbortController()
    const signal = controller.signal
    let timer = setTimeout(() => {
      controller.abort()
      ElMessage('请求超时')
    }, 6000);

    fetch(url, {
      credentials: 'include',
      method: 'GET',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      signal,
      ...option
    }).then(async (response: Response) => {
     clearTimeout(timer)
     needLoading && commonStore.decreaseRequestTimes()

      try {
        const json = await response.json() ?? {}

        resolve(json)
      } catch (err) {
        console.log(err)
      }
    }, (err: Error) => {
      clearTimeout(timer)
      needLoading && commonStore.decreaseRequestTimes()
      console.log(err)
    })
  })
}